package com.xbongbong.paas.service.dynamic.crm.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.service.dynamic.crm.strategy.AbstractDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.TeamDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.customercommunicate.pojo.dto.DynamicDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailRenameDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicEditTeamDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicTeamDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicTeamLabelDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicTeamUpdateDTO;
import com.xbongbong.pro.enums.teammembers.enums.CoUserPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.pojo.TeamSaveMiddlePojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ListBatchConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.UserTeamOperateTagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.impl.TeamDetailServiceImpl;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *团队
 *
 *@author weijianxun
 */
@Service("teamDynamicStrategyImpl")
public class TeamDynamicStrategyImpl extends AbstractDynamicStrategy implements TeamDynamicStrategy {

    private final Logger LOG = LoggerFactory.getLogger(TeamDynamicStrategyImpl.class);

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),
                XbbRefTypeEnum.CONTACT.getCode(),
                XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(),
                XbbRefTypeEnum.CONTRACT.getCode());
    }

    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasFormModel paasFormModel;

    /**
     * {@link TeamDetailServiceImpl#renameTeam(com.xbongbong.pro.detailtab.dto.team.TeamDetailRenameDTO)}
     * 目前编辑团队名称，只存在隔离模式下的客户和线索业务
     * @param dynamicEditTeamDTO
     */
    @Override
    @Async("dynamicThreadPool")
    public void editTeamName(DynamicEditTeamDTO dynamicEditTeamDTO) {
        try {
            TeamDetailRenameDTO teamDetailRenameDTO = dynamicEditTeamDTO.getTeamDetailRenameDTO();
            Integer businessType = teamDetailRenameDTO.getBusinessType();

            if (!isMainBusinessType(businessType)) {
                return;
            }

            Long formId = teamDetailRenameDTO.getFormId();
            String corpid = teamDetailRenameDTO.getCorpid();
            UserVO loginUser = teamDetailRenameDTO.getLoginUser();
            String userName = loginUser.getName();
            String userId = loginUser.getUserId();

            UserEntity userEntity = dynamicEditTeamDTO.getUserEntity();
            String opObjectName = userEntity.getName();

            CustomerEntityExt customerEntityExt = dynamicEditTeamDTO.getCustomerEntityExt();
            Integer subType = ProjectLogEnum.teamLogSubTypeByBusinessType(businessType, OperateTypeEnum.EDIT);
            if (!Objects.equals(subType, ProjectLogEnum.UNKNOW.getSubType())) {
                PaasFormEntity paasForm = getPaasForm(corpid, formId, businessType);
                DynamicDTO dynamicDTO = initDynamicDTO(userId, CrmLogMemoConstant.DYNAMIC_USER_TEAM_UPDATE_TEAM_NAME, subType, DynamicDTO.initMemoHolder(userName, opObjectName),
                        paasForm, teamDetailRenameDTO.getSaasMark(), customerEntityExt.getId());
                insertDynamic(Collections.singletonList(dynamicDTO), corpid);
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.TeamDynamicStrategyImpl.editTeamName", e);
        }
    }

    /**
     * 动态
     * @param dynamicTeamDTO
     * @throws XbbException
     */

    @Override
    @Async("dynamicThreadPool")
    public void dynamic(DynamicTeamDTO dynamicTeamDTO) {
        try {
            TeamAfterVerifyDTO teamAfterVerifyDTO = dynamicTeamDTO.getTeamAfterVerifyDTO();

            if (!isMainBusinessType(teamAfterVerifyDTO.getBusinessType()) || teamAfterVerifyDTO.getLoginUser() == null) {
                return;
            }

            Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
            Map<String, Set<String>> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap();
            Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
            Map<String, Set<String>> delCoUserMap = teamAfterVerifyDTO.getDelCoUserMap();
            Map<String, Set<String>> updateToMainUserMap = teamAfterVerifyDTO.getUpdateToMainUserMap();
            Map<String, Set<String>> updateToCoUserMap = teamAfterVerifyDTO.getUpdateToCoUserMap();
            String operatorName = teamAfterVerifyDTO.getLoginUser().getName();
            Integer operatorId = teamAfterVerifyDTO.getLoginUser().getId();
            String corpId = teamAfterVerifyDTO.getCorpid();
            Long formId = teamAfterVerifyDTO.getFormId();
            Integer operateTag = teamAfterVerifyDTO.getOperateTag();
            Integer model = teamAfterVerifyDTO.getFormTeamSetEntity().getModel();
            Integer businessType = teamAfterVerifyDTO.getBusinessType();
            //查询一下表单信息
            String formName;
            PaasFormEntityExt paasFormEntityExt = null;
            if (Objects.equals(teamAfterVerifyDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, teamAfterVerifyDTO.getCorpid());
                formName = workOrderFormEntityExt.getName();
            } else {
                paasFormEntityExt = paasFormModel.getByKey(formId, corpId);
                formName = paasFormEntityExt.getName();
            }
            //业务详情界面的时候会传进来的参数
            // Map<Long, PaasFormDataEntity> paasFormDataEntityExtMap = teamAfterVerifyDTO.getPaasFormDataEntityExtMap();

            List<Long> dataIdIn = teamAfterVerifyDTO.getDataId();
            if (CollectionUtils.isEmpty(dataIdIn)) {
                return;
            }
            TeamSaveMiddlePojo teamSaveMiddlePojo = teamAfterVerifyDTO.getTeamSaveMiddlePojo();

            List<DynamicDTO> dynamicDTOS = new ArrayList<>(dataIdIn.size());

            PaasFormEntity paasForm = new PaasFormEntity();
            BeanUtil.copyProperties(paasFormEntityExt, paasForm);
            List<Long> deepCloneDataIdIn = new ArrayList<>();
            deepCloneDataIdIn = (List<Long>)CloneUtil.deepClone(dataIdIn);
            for (Long dataId : deepCloneDataIdIn) {
                if (Objects.nonNull(teamSaveMiddlePojo) && Objects.nonNull(teamSaveMiddlePojo.getPaymentSheetSonDataIdList()) &&
                        teamSaveMiddlePojo.getPaymentSheetSonDataIdList().contains(dataId)) {
                    //这边主要是回款单的特殊逻辑
                    continue;
                }
                //这个主要是新增主业务的时候会传的参数
                // PaasFormDataEntity paasFormDataEntity = teamAfterVerifyDTO.getPaasFormDataEntity();
                // if (Objects.isNull(paasFormDataEntity)) {
                //     paasFormDataEntity = paasFormDataEntityExtMap.get(dataId);
                // }
                // paasFormDataEntity = teamDataHelp.entityTransfer(paasFormDataEntity, businessType);
                Set<String> addMainUserList = Objects.isNull(addMainUserMap) ? null : addMainUserMap.get(String.valueOf(dataId));
                Set<String> addCoUserList = Objects.isNull(addCoUserMap) ? null : addCoUserMap.get(String.valueOf(dataId));
                Set<String> delMainUserList = Objects.isNull(delMainUserMap) ? null : delMainUserMap.get(String.valueOf(dataId));
                Set<String> delCoUserList = Objects.isNull(delCoUserMap) ? null : delCoUserMap.get(String.valueOf(dataId));
                Set<String> updateToCoUserList = Objects.isNull(updateToCoUserMap) ? null : updateToCoUserMap.get(String.valueOf(dataId));
                Set<String> updateToMainUserList = Objects.isNull(updateToMainUserMap) ? null : updateToMainUserMap.get(String.valueOf(dataId));

                UserVO userVO = teamAfterVerifyDTO.getLoginUser();
                DynamicDTO dynamicDTO = new DynamicDTO();
                // String saveName = abstractTeamStrategy.getSaveName(corpId, teamAfterVerifyDTO.getBusinessType(), paasFormEntityExt, paasFormDataEntity);
                String saveName = null;
                //新增负责人和新增团队和移交负责人都有addMainUserList,所以下面需要两层区分：（1）第一层根据addMainUserList区分（2）第二层根据operateTag去区分
                try {
                    if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
                        teamDynamic(dynamicDTO, addMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.NEW, operateTag, null, null, null, formName, saveName, businessType);
                    } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
                        teamDynamic(dynamicDTO, delMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.DELETE, operateTag, null, null, null, formName, saveName, businessType);
                    } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
                        //移交-》需要区分隔离模式和共享模式; 原负责人信息存在delMainUserList
                        // 隔离模式：替换后的负责人信息存在addMainUserList
                        // 共享模式：替换后的负责人信息可能存在updateToMainUserList、addMainUserList
                        if (CollectionUtils.isEmpty(delMainUserList)) {
                            continue;
                        }
                        String originUserId = delMainUserList.stream().findFirst().get();
                        String changeUserId = null;
                        if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                            changeUserId = addMainUserList.stream().findFirst().get();
                        } else {
                            if (CollectionsUtil.isNotEmpty(updateToMainUserList)) {
                                changeUserId = updateToMainUserList.stream().findFirst().get();
                            } else {
                                changeUserId = addMainUserList.stream().findFirst().get();
                            }
                        }
                        //如果是移交给团队内的协同人，则addMainUserList为null，补丁一下
                        if (CollectionUtils.isNotEmpty(updateToMainUserMap.get(String.valueOf(dataId)))) {
                            teamDynamic(dynamicDTO, updateToMainUserMap.get(String.valueOf(dataId)), operatorId, corpId, operatorName, OperateTypeEnum.HANDOVER, operateTag, originUserId, changeUserId, model, formName, saveName, businessType);
                        } else {
                            teamDynamic(dynamicDTO, addMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.HANDOVER, operateTag, originUserId, changeUserId, model, formName, saveName, businessType);
                        }
                        //移交操作的时候需要判断如果是客户或者线索的业务则需要进行消息推送
                        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)
                                || Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)) {
                            //推送+移交
                            //changeMainPush(teamAfterVerifyDTO, saveName, paasFormDataEntity, originUserId, changeUserId);
                        }

                    } else {
                        if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                            operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                            teamDynamic(dynamicDTO, addMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.NEW, operateTag, null, null, null, formName, saveName, businessType);
                        }

                        //新增协同人
                        else if (addCoUserList != null && !addCoUserList.isEmpty()) {
                            //日志操作flag:0为新增,1为删除,2为修改,3移交
                            operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                            teamDynamic(dynamicDTO, addCoUserList, operatorId, corpId, operatorName, OperateTypeEnum.NEW, operateTag, null, null, null, formName, saveName, businessType);
                        }

                        //删除负责人
                        else if (CollectionsUtil.isNotEmpty(delMainUserList)) {
                            //日志操作flag:0为新增,1为删除,2为修改,3移交
                            operateTag = UserTeamOperateTagEnum.DEL_MAIN.getOperateTag();
                            teamDynamic(dynamicDTO, delMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.DELETE, operateTag, null, null, null, formName, saveName, businessType);
                        }

                        //删除协同人
                        else if (delCoUserList != null && !delCoUserList.isEmpty()) {
                            //日志操作flag:0为新增,1为删除,2为修改,3移交
                            operateTag = UserTeamOperateTagEnum.DEL_COUSER.getOperateTag();
                            teamDynamic(dynamicDTO, delCoUserList, operatorId, corpId, operatorName, OperateTypeEnum.DELETE, operateTag, null, null, null, formName, saveName, businessType);
                        }

                        //负责人变更(将负责人变成协同人)，记录日志是按照新增协同人日志去操作的
                        else if (updateToCoUserList != null && !updateToCoUserList.isEmpty()) {
                            //日志操作flag:0为新增,1为删除,2为修改,3移交
                            operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                            teamDynamic(dynamicDTO, updateToCoUserList, operatorId, corpId, operatorName, OperateTypeEnum.EDIT, operateTag, null, null, null, formName, saveName, businessType);
                        }

                        //协同人变更（将协同人变成负责人）,记录日志按照新增负责人日志去操作
                        else if (updateToMainUserList != null && !updateToMainUserList.isEmpty()) {
                            //日志操作flag:0为新增,1为删除,2为修改,3移交
                            operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                            teamDynamic(dynamicDTO, updateToMainUserList, operatorId, corpId, operatorName, OperateTypeEnum.EDIT, operateTag, null, null, null, formName, saveName, businessType);
                        }
                    }
                } catch (Exception e) {
                    LOG.error("团队动态填充失败", e);
                    continue;
                }

                if (StringUtil.isNotEmpty(dynamicDTO.getMemo()) && userVO != null) {
                    DynamicDTO insertDynamic;
                    try {
                        insertDynamic = initDynamicDTO(userVO.getUserId(), null, dynamicDTO.getLogType(), null, paasForm, teamAfterVerifyDTO.getSaasMark(), dataId);
                        BeanUtil.copyProperties(dynamicDTO, insertDynamic, true);
                        dynamicDTOS.add(insertDynamic);
                    } catch (Exception e) {
                        // 线上一直报空指针排查一下
                        if (e instanceof NullPointerException) {
                            LOG.error("userVo是null?,{}", JSON.toJSONString(userVO));
                            LOG.info("dynamicDTO是null?,{}", JSON.toJSONString(dynamicDTO));
                        }
                        throw e;
                    }
                }

            }

            insertDynamic(dynamicDTOS, corpId);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.TeamDynamicStrategyImpl.dynamic", e);
        }
    }

    /**
     * 团队动态
     */
    private void teamDynamic(DynamicDTO dynamicDTO, Set<String> userList, Integer operatorId, String corpId, String operatorName,
                             OperateTypeEnum operateTypeEnum , Integer operateTag, String originUserId, String changeUserId, Integer model,
                             String xbbRefTypeName, String saveName, Integer businessType) {
        String isMainStr = null;
        //关键词封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            // isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            // isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        }

        Integer subType = ProjectLogEnum.teamLogSubTypeByBusinessType(businessType, operateTypeEnum);
        if (ProjectLogEnum.UNKNOW.getSubType().equals(subType)) {
            throw new RuntimeException("team dynamic invalid subtype:" + subType);
        }
        dynamicDTO.setLogType(subType);

        //查询用户相关信息、操作对象
        List<UserEntity> userEntityList = null;
        String userNameListStr = null;
        String operateObjectName = null;
        String afterOwnName = null;
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            userEntityList = userModel.getByUserIdIn(corpId, Arrays.asList(originUserId, changeUserId), false);
            for (UserEntity userEntity : userEntityList) {
                if (Objects.equals(userEntity.getUserId(), changeUserId)) {
                    operateObjectName = userEntity.getName();
                } else {
                    afterOwnName = userEntity.getName();
                }
            }
        } else {
            userEntityList = userModel.getByUserId(CollectionUtils.isNotEmpty(userList) ? new ArrayList<>(userList) : new ArrayList<>(), corpId);
            List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            userEntityList.forEach(user -> userNameList.add(user.getName()));
            userNameListStr = StringUtils.join(userNameList, "、");
            // if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag()) ||
            //         Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            //     operateObjectName = StringUtils.join(userNameList, "、") + I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_SUFFIX);
            //     ;
            // } else {
            //     operateObjectName = StringUtils.join(userNameList, "、");
            // }
        }

        //下面对message进行封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_ADD);
            if(StringUtil.isEmpty(userNameListStr)){
                throw new RuntimeException("新建协同负责人存在异常");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, userNameListStr));
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_DELETE);
            if(StringUtil.isEmpty(userNameListStr)){
                throw new RuntimeException("删除协同负责人存在异常");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, userNameListStr));
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_COUSER.getOperateTag())) {
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_ADD_TEAM);
            if(StringUtil.isEmpty(userNameListStr)){
                throw new RuntimeException("创建团队存在异常，XXX已存在于团队中，该异常在com.xbongbong.paas.service.team.TeamDataHelp.save");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, userNameListStr));
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_BREAK_TEAM);
            if(StringUtil.isEmpty(userNameListStr)){
                throw new RuntimeException("解散团队存在异常，至少保存一个团队，该异常在com.xbongbong.paas.service.team.TeamDataHelp.save");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, userNameListStr));
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
            // dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_ISOLATION_HANDOVER);
            // dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, xbbRefTypeName, isMainStr, afterOwnName, operateObjectName));
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_SHARE_HANDOVER);
            if(StringUtil.isEmpty(operateObjectName)){
                throw new RuntimeException("团队移交隔离存在异常");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, afterOwnName, operateObjectName));
        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_SHARE.getModel())) {
            dynamicDTO.setMemo(CrmLogMemoConstant.DYNAMIC_USER_TEAM_SHARE_HANDOVER);
            if(StringUtil.isEmpty(operateObjectName)){
                throw new RuntimeException("团队移交分享存在异常");
            }
            dynamicDTO.setMemoPlaceHolder(DynamicDTO.initMemoHolder(operatorName, isMainStr, afterOwnName, operateObjectName));
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void saveUpdateCoPerDynamic(DynamicTeamUpdateDTO dynamicTeamUpdateDTO) {
        try {
            TeamDetailUpdateDTO teamDetailUpdateDTO = dynamicTeamUpdateDTO.getTeamDetailUpdateDTO();

            if (!isMainBusinessType(teamDetailUpdateDTO.getBusinessType())) {
                return;
            }

            UserTeamEntity userTeamEntity = dynamicTeamUpdateDTO.getUserTeamEntity();

            Integer subType = ProjectLogEnum.teamLogSubTypeByBusinessType(teamDetailUpdateDTO.getBusinessType(), OperateTypeEnum.EDIT);
            if (ProjectLogEnum.UNKNOW.getSubType().equals(subType)) {
                return;
            }

            Long dataId = teamDetailUpdateDTO.getDataId();
            String corpid = teamDetailUpdateDTO.getCorpid();

            UserEntity userEntity = userModel.getByKey(userTeamEntity.getUserId(), corpid);
            String userName = teamDetailUpdateDTO.getLoginUser().getName();
            String content;
            if (Objects.equals(teamDetailUpdateDTO.getFormPermission(), CoUserPermissionEnum.EDIT.getPermissionValue())) {
                content = I18nMessageUtil.getMessage(TeamMembersConstant.EDIT);
            } else {
                content = I18nMessageUtil.getMessage(TeamMembersConstant.NO_EDIT);
            }
            PaasFormEntity paasForm = getPaasForm(corpid, teamDetailUpdateDTO.getFormId(), teamDetailUpdateDTO.getBusinessType());
            DynamicDTO dynamicDTO = initDynamicDTO(teamDetailUpdateDTO.getLoginUser().getUserId(), CrmLogMemoConstant.DYNAMIC_USER_TEAM_UPDATE_COR_PERMISSION, subType, DynamicDTO.initMemoHolder(userName, userEntity.getName(), content),
                    paasForm, teamDetailUpdateDTO.getSaasMark(), dataId);
            insertDynamic(Collections.singletonList(dynamicDTO), corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.TeamDynamicStrategyImpl.editCoPermission", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void saveUpdateLabelDynamic(DynamicTeamLabelDTO dynamicTeamLabelDTO) {
        try {
            UserTeamEntity userTeamEntity = dynamicTeamLabelDTO.getUserTeamEntity();
            TeamDetailEditLabelDTO teamDetailEditLabelDTO = dynamicTeamLabelDTO.getTeamDetailEditLabelDTO();
            Integer businessType = teamDetailEditLabelDTO.getBusinessType();

            if (!isMainBusinessType(businessType)) {
                return;
            }

            String corpid = teamDetailEditLabelDTO.getCorpid();
            String userId = userTeamEntity.getUserId();
            Integer isMain = userTeamEntity.getIsMain();
            Long formId = teamDetailEditLabelDTO.getFormId();
            UserVO loginUser = teamDetailEditLabelDTO.getLoginUser();
            Integer saasMark = teamDetailEditLabelDTO.getSaasMark();
            Long dataId = teamDetailEditLabelDTO.getDataId();

            Integer subType = ProjectLogEnum.teamLogSubTypeByBusinessType(businessType, OperateTypeEnum.EDIT);
            if (ProjectLogEnum.UNKNOW.getSubType().equals(subType)) {
                return;
            }
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            String content;
            if (Objects.equals(isMain, BasicConstant.ONE)) {
                content = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
            } else {
                content = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
            }
            PaasFormEntity paasForm = getPaasForm(corpid, formId, businessType);
            DynamicDTO dynamicDTO = initDynamicDTO(loginUser.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_TEAM_UPDATE_TAG, subType,
                    DynamicDTO.initMemoHolder(loginUser.getName(), content, userEntity.getName()), paasForm, saasMark, dataId);
            insertDynamic(Collections.singletonList(dynamicDTO), corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.TeamDynamicStrategyImpl.saveUpdateLabelDynamic", e);
        }
    }
}
